// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init();

var http = require('http');
var iconv = require('iconv-lite');
var superagent = require("superagent");
var cheerio = require("cheerio");
var charset = require("superagent-charset");

var url = "http://www.gdmec.cn/xwzx/xxyw.htm";
var return_msg;

function index(){
  var json = [];
  superagent.get(url)
    .then(res => {
      var body = res.text;
      console.log(res.text);
      var $ = cheerio.load(body);
      var items = $('.list_ccc').find('li').map(function () {
        var id = $(this)[0]["attribs"]["id"].split('_')[2];
        id = parseInt(id)
        console.log(url.indexOf("xxyw.htm"));
        if ((id >= 7 && id <= 26) || url.indexOf("xxyw.htm") != -1)
        {
          var title_html = $(this).find('a').text();
          var time_html = $(this).find('span').text();
          var href_html = $(this).find('a')[0]["attribs"]["href"];
          var ls_json = {
            "title":title_html,
            "time":time_html,
            "href":href_html
          }
          json.push(ls_json);
        }
      });
      var next = $('.Next');
      if (next.length > 0) {
        next = next[0]["attribs"]["href"];
      }
      return_msg = {
        error: 0,
        data: json,
        next:next
      }
    }).catch(err => {
      return_msg = { "error": 1, "msg": "获取新闻列表失败" }
    });
}
//获取新闻详情
function getnews(href)
{
  var json = [];
  if(href.indexOf("../../") != -1)
  {
    url = "http://www.gdmec.cn/xwzx/a/" + href;
  }
  else
  {
    url = "http://www.gdmec.cn/xwzx/" + href;
  }
  superagent.get(url)
    .then(res => {
      var body = res.text;
      console.log(res.text);
      var $ = cheerio.load(body);
      var items = $('.v_news_content').find('p').map(function () {
        var img_html = $(this).find('img');
        if(img_html.length != 0)
        {
          var img_url = (img_html[0]["attribs"]["src"]);
          if (img_url.indexOf("https") == -1 && img_url.indexOf("http") == -1)
          {
            img_url = "http://www.gdmec.cn" + img_url;
          }
          json.push({
            lx:"img",
            src:img_url
          })
        }
        else
        {
          var content = $(this).text();
          if (content != " ")
          {
            json.push({
              lx: "text",
              content: content
            })
          }
        }
      });
      return_msg = {
        error:0,
        data:json
      }
    }).catch(err => {
      return_msg = { "error": 1, "msg": "获取新闻详情失败" }
    });
}
//入口模块
function rkhs(event) {
  if (event.type == "get_news_title") {
    if (event.href == "" || event.href == undefined) {
      if (event.hrefs == "" || event.hrefs == undefined) {
       url = "http://www.gdmec.cn/xwzx/xxyw.htm";
      }
      else{
        url = "http://www.gdmec.cn/" + event.hrefs;
      }
    }
    else
    {
      if (event.href.indexOf("xxyw") != -1 || event.href.indexOf("xykx") != -1 || event.href.indexOf("mtgz") != -1 || event.href.indexOf("tzgg") != -1 || event.href.indexOf("kydt") != -1 || event.href.indexOf("gzzx") != -1)
      {
        url = "http://www.gdmec.cn/xwzx/" + event.href;
      }
      else
      {
        url = "http://www.gdmec.cn/xwzx/xxyw/" + event.href;
      }
    }
    index();
  }
  if (event.type == "get_news") {
    if(event.href == "" || event.href == undefined)
    {
      return_msg = { "error": 1, "msg": "请传参数" }
    }
    else
    {
      getnews(event.href);
    }
  }
  var count = 0
  return new Promise((resolve, reject) => {
    // 在 3 秒后返回结果给调用方（小程序 / 其他云函数）
    var timer = setInterval(() => {
      if(count < 6)
      {
        if (return_msg == "") {
          count++;
        }
        else {
          resolve(return_msg)
        }
      }
      else
      {
        clearInterval(timer);
        if (return_msg == "") {
          return_msg = { "error": 1, "msg": "请求超时,请重试" }
          resolve(return_msg)
        }
        else {
          resolve(return_msg)
        }
      }
    }, 1000)
  })
}

// 云函数入口函数
exports.main = async (event, context) => {
  return_msg = "";
  if (event.type != "") {
    return rkhs(event);
  }
  else
  {
    return { "error": 1, "msg": "请传参数" }
  }
}